<style scoped>
.padding5 {
  padding: 5px;
}
.tableScroll {
  overflow: hidden;
}
.ivu-modal-footer {
  display: none;
}

</style>
<template>
  <Card>
    <div>
      <Row style="text-align:left;padding:10px 0;">
        <Col span="6">
        <Input v-model="queryStr" placeholder="类型/品牌/测能类型">
        <Button slot="append" icon="ios-search" type="info" @click.native="query(queryStr)"></Button>
        </Input>
        </Col>
        <Col span="18" style="text-align:right;">
          <div style="display: inline-flex;width: 600px;" v-if="uploadFile !== null">
              <div style="flex: 5;text-align: right;padding-right: 10px;">
                  <span style="font-size: 18px;">已选文件:  {{ uploadFile.name }}</span>
              </div>
              <div style="flex: 1;margin-top: 0px;">
                    <Button type="success" @click="doUpload" :loading="upLoadingStatus">
                      {{upLoadingStatus?'正在上传':'确认上传'}}
                    </Button>
              </div>
          </div>
          <Upload style="display: inline-flex;" :before-upload="beforeDoUpload" action="" accept=".xlsx">
            <Button type="info" icon="ios-download-outline" :disabled="upLoadingStatus">选择导入</Button>
          </Upload>
        <Button type="info" @click="exportData(1)" icon="ios-download-outline">导出</Button>
        <Button type="success" icon="ios-add-circle-outline" @click.native="add()">新增</Button>
        <Button type="error" icon="ios-trash-outline" :disabled="deleteMoreDisabled" @click.native="deleteMoreBtn()">删除</Button>
        </Col>
      </Row>
      <Table :loading="spinShow" border :columns="columns7" :data="tableList" ref="table" @on-selection-change="tableCheckbox"></Table>
      <Row style="text-align:right;padding:10px 0;">
        <Page :total="pageObj.total" size="small" show-elevator :page-size="pageObj.size" @on-change="pageChange" @on-page-size-change="pageSizeChange"></Page>
      </Row>
    </div>
    <Modal v-model="modal1" :title="modalTitle" width="820" @on-cancel="cancel" @on-ok="ok" :scrollable="true">
      <Tabs :value="showTabPanel" type="card">
        <TabPane name="oneTab" label="设备信息" class="padding5">
          <DeviceManageForm ref="refDeviceInfoForm" @showTab="showTab" @saveSubmitReady="saveSubmitReady" @updSubmitReady="updSubmitReady"></DeviceManageForm>
        </TabPane>
        <TabPane name="twoTab" label="采集项" class="padding5">
          <CollectionForm ref="refDeviceColForm" @showTab="showTab" @saveSubmitReady="saveSubmitReady" @updSubmitReady="updSubmitReady"></CollectionForm>
        </TabPane>
      </Tabs>
      <div slot="footer" style="display:none;">
        <!-- <Button type="info" @click="modal1=!modal1">关闭</Button> -->
      </div>
    </Modal>
  </Card>
</template>
<script>
import DeviceManageForm from '../manage/DeviceManageForm.vue'
import CollectionForm from '../manage/CollectionForm.vue'
export default {
  components: { DeviceManageForm, CollectionForm },
  data: function () {
    let self = this
    return {
      editOneData: {},
      pageObj: { total: 0, size: 20, index: 0 },
      childObj: {},
      showTabPanel: 'oneTab',
      spinShow: true,
      upLoadingStatus: false,
      uploadFile: null,
      tableList: [],
      totalElements: 0,
      queryStr: '',
      modal1: false,
      modalTitle: '',
      value13: '',
      columns7: [{
        type: 'selection',
        width: 60,
        align: 'center',
        render: (h, params) => {
          let txt = ''
          return h('div', [
            h('span', txt)
          ])
        }
      }, {
        type: 'index',
        align: 'center'
      }, {
        title: '名称',
        key: 'name',
        ellipsis: true,
        tooltip: true,
        align: 'center'
      }, {
        title: '类型',
        key: 'iotDevType',
        align: 'center',
        render: (h, params) => {
          let txt = ''
          if (params.row.iotDevType) {
            txt = params.row.iotDevType.useType
          }
          return h('div', [
            h('span', txt)
          ])
        }
      }, {
        title: '型号',
        key: 'iotDevType',
        align: 'center',
        render: (h, params) => {
          let txt = ''
          if (params.row.iotDevType) {
            txt = params.row.iotDevType.model
          }
          return h('div', [
            h('span', txt)
          ])
        }
      }, {
        title: '编号',
        key: 'id',
        maxWidth: 100,
        align: 'center'
      }, {
        title: '品牌',
        key: 'iotDevType',
        align: 'center',
        render: (h, params) => {
          let txt = ''
          if (params.row.iotDevType) {
            txt = params.row.iotDevType.brand
          }
          return h('div', [
            h('span', txt)
          ])
        }
      }, {
        title: '所属空间',
        key: 'iotSpace',
        ellipsis: true,
        tooltip: true,
        align: 'center',
        render: (h, params) => {
          let txt = ''
          if (params.row.iotSpace) {
            txt = params.row.iotSpace.name
          }
          return h('div', [
            h('span', txt)
          ])
        }
      }, {
        title: '状态',
        key: 'debugStat',
        align: 'center'
      }, {
        title: '操作',
        key: 'action',
        maxWidth: 350,
        minWidth: 300,
        align: 'center',
        render: (h, params) => {
          return h('div', [
            h('Button', {
              props: {
                // type: 'text',
                size: 'small'
              },
              style: {
                margin: '3px',
                color: '#2db7f5'
              },
              on: {
                click: () => {
                  let self = this
                  let config = {
                    title: '提示',
                    content: '您确定删除吗？',
                    onOk: function () {
                      self.deleteOne(params.row.id)
                    }
                  }
                  this.$Modal.confirm(config)
                }
              }
            }, '删除'),
            h('Button', {
              props: {
                // type: 'text',
                size: 'small'
              },
              style: {
                margin: '3px',
                color: '#2db7f5'
              },
              on: {
                click: () => {
                  self.edit(params.row)
                }
              }
            }, '编辑'),
            h('Button', {
              props: {
                // type: 'text',
                size: 'small'
              },
              style: {
                margin: '3px',
                color: '#2db7f5'
              },
              on: {
                click: () => {
                  this.show(params.index)
                }
              }
            }, '调试设备'),
            h('Button', {
              props: {
                // type: 'text',
                size: 'small'
              },
              style: {
                margin: '3px',
                color: '#2db7f5'
              },
              on: {
                click: () => {
                  this.show(params.index)
                }
              }
            }, '查看设备配置')
          ])
        }
      }],
      tableCheckboxData: [],
      deleteMoreDisabled: true
    }
  },
  created: function () {
    this.list()
  },
  mounted: function () {
    // console.log('--mounted--')
  },
  destroyed: function () {
    this.$Message.destroy()
  },
  methods: {
    show: function (index) {
      this.$Modal.info({
        title: '设备信息',
        content: `名称：${this.tableList[index].name}<br>
        IP地址：${this.tableList[index].commAddr}<br>
        状态：${this.tableList[index].debugStat}<br>
        ----设备类型----<br>
        品牌：${this.tableList[index].iotDevType.brand}<br>
        型号：${this.tableList[index].iotDevType.model}<br>
        协议：${this.tableList[index].iotDevType.prol}<br>
        类型：${this.tableList[index].iotDevType.useType}<br>
        读取间隔：${this.tableList[index].iotDevType.readInterval}<br>
        ----设备空间----<br>
        名字：${this.tableList[index].iotSpace.name}<br>
        备注:${this.tableList[index].iotSpace.remark}`
      })
    },
    remove: function (index) {
      this.tableList.splice(index, 1)
    },
    doUpload: function () {
      if (this.uploadFile === null) {
        this.$Message.info('无法获上传的文件')
        return
      }
      let formData = new FormData()
      formData.append('file', this.uploadFile)
      this.upLoadingStatus = true
      window.myapi.upload('iot/dev/import',formData).then(resp => {
        if (resp.status === 200 && resp.data.status === 200) {
          this.$Notice.success({
            title: '操作提示',
            desc: '已成功上传' + resp.data.data + '条数据'
          })
          // 刷新数据
          this.list()
        } else {
          this.$Notice.warning({
            title: '操作提示',
            desc: resp.data.msg
          })
        }
      }).catch(error => {
        this.$Notice.warning({
          title: '操作提示',
          desc: error
        })
      }).finally(() => {
        this.upLoadingStatus = false
      })
    },
    beforeDoUpload: function (file) {
      this.uploadFile = file
      return false
    },
    exportData: function () {
      let self = this
      // 处理为标准格式
      let columns7Tem = [{
        type: 'selection',
        width: 60,
        align: 'center'
      }, {
        type: 'index',
        width: 60,
        align: 'center'
      }, {
        title: '类型',
        key: 'useType',
        align: 'center'
      }, {
        title: '型号',
        key: 'model',
        align: 'center'
      }, {
        title: '编号',
        key: 'id',
        align: 'center'
      }, {
        title: '品牌',
        key: 'brand',
        align: 'center'
      }, {
        title: '所属空间',
        key: 'name',
        align: 'center'
      }, {
        title: '状态',
        key: 'debugStat',
        align: 'center'
      }, {
        title: '操作',
        key: 'action',
        width: 150,
        align: 'center'
      }]
      self.$refs.table.exportCsv({
        filename: '设备管理数据',
        columns: columns7Tem,
        data: self.tableList.map((data, index) => {
          // 数据处理为标准格式
          let tem = JSON.parse(JSON.stringify(data))
          let obj = {
            useType: tem.iotDevType.useType,
            model: tem.iotDevType.model,
            id: tem.id,
            brand: tem.iotDevType.brand,
            name: tem.iotSpace.name,
            debugStat: tem.debugStat
          }
          return obj
        })
      })
    },
    modalShow: function () {
      this.modal1 = true
    },
    modalHide: function () {
      this.modal1 = false
    },
    ok: function () {
      /* this.$Message.info('Clicked ok') */
    },
    cancel: function () {
      /* this.$Message.info('Clicked cancel') */
    },
    // 数据list
    list: function () {
      let self = this
      let getData = {
        'size': self.pageObj.size,
        'page': self.pageObj.index,
        'searchParam': self.queryStr
      }
      self.spinShow = true
      window.myapi.dev_list(getData).then(function (res) {
        self.tableList = []
        if (res.data.status === 200) {
          self.tableList = res.data.data.content
          self.totalElements = res.data.data.totalElements
          self.pageObj.size = res.data.data.size
          self.pageObj.total = res.data.data.totalElements
        } else {
          let msg = res.data.msg ? res.data.msg : '请求数据失败!'
          self.$Message.error({ content: msg, duration: 5, closable: true })
        }
        self.spinShow = false
      }).catch(function (e) {
        if (e && e.response && e.response.data) {
          let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
          self.$Message.error({ content: msg, duration: 5, closable: true })
          self.tableList = []
          self.spinShow = false
        }
      })
    },
    // 第几页
    pageChange: function (index) {
      let self = this
      self.pageObj.index = index - 1
      self.list()
    },
    // 每页显示多少
    pageSizeChange: function (index) {
      console.log(index)
    },
    // 删除
    deleteOne: function (id) {
      let self = this
      let arr = []
      arr.push(id)
      self.deleteMore(arr)
    },
    // 删除
    deleteMore: function (arr) {
      let self = this
      let postData = arr
      window.myapi.dev_del(postData).then(function (res) {
        if (res.data.status === 200) {
          self.$Message.error('删除数据成功!')
          self.list()
        } else {
          let msg = res.data.msg ? res.data.msg : '删除数据失败!'
          self.$Message.error(msg)
        }
      }).catch(function (e) {
        let msg = e.response.data.message ? e.response.data.message : '删除数据失败!'
        self.$Message.error({ duration: 0, closable: true, content: msg })
      })
    },
    // 查询
    query: function (str) {
      let self = this
      if (str) {
        self.queryStr = str
        self.pageObj.index = 0
      } else {
        self.queryStr = ''
      }
      self.list()
    },
    // 新增弹框
    add: function () {
      let self = this
      self.modalTitle = '新增'
      self.modalShow()
      self.resetModalData()
      self.$refs.refDeviceInfoForm.updateFormdata({})
      self.$refs.refDeviceColForm.updateFormdata({})
      self.editOneData = {}
    },
    // 编辑
    edit: function (data) {
      let self = this
      self.modalTitle = '编辑'
      self.modalShow()
      self.resetModalData()
      self.$refs.refDeviceInfoForm.updateFormdata(data)
      self.$refs.refDeviceColForm.updateFormdata(data)
      self.editOneData = data
    },
    // 新增
    save: function () {
      let self = this
      let postData = self.childObj
      window.myapi.dev_save(postData).then(function (res) {
        if (res.data.status === 200) {
          self.$Message.success('保存成功!')
          self.modalHide()
          self.resetModalData()
          self.pageObj.index = 0
          self.query()
        } else {
          let msg = res.data.msg ? res.data.msg : '保存失败！'
          self.$Message.error(msg)
        }
      }).catch(function (e) {
        let msg = e.response.data.message ? e.response.data.message : '保存失败!'
        self.$Message.error({ duration: 0, closable: true, content: msg })
      })
    },
    // 修改
    upd: function () {
      let self = this
      let postData = self.childObj
      window.myapi.dev_upd(postData).then(function (res) {
        if (res.data.status === 200) {
          self.$Message.success('保存成功!')
          self.modalHide()
          self.resetModalData()
          self.query()
        } else {
          let msg = res.data.msg ? res.data.msg : '保存失败！'
          self.$Message.error(msg)
        }
      }).catch(function (e) {
        let msg = e.response.data.message ? e.response.data.message : '保存失败!'
        self.$Message.error({ duration: 0, closable: true, content: msg })
      })
    },
    // 显示的tab
    showTab: function (chirldData) {
      let self = this
      if (chirldData.objStr) {
        // 存储form里面的数据
        let obj = JSON.parse(chirldData.objStr)
        self.childObj.name = obj.name
        self.childObj.model = obj.model
        self.childObj.commAddr = obj.commAddr
        self.childObj.readInterval = obj.readInterval
        self.childObj.iotSpace = obj.iotSpace
        self.childObj.iotDevType = obj.iotDevType
        self.childObj.iotDevType.iotCollItems.forEach((item) => {
          if (item.isGet === true || item.isGet === 'true') {
            item.isGet = 1
          } else {
            item.isGet = 0
          }
        })
        if (obj.debugStat) {
          self.childObj.debugStat = obj.debugStat
        }
        if (obj.id !== undefined) {
          self.childObj.id = obj.id
        }
      }
      /* if (chirldData.arrStr) {
        // 存储form里面的数据
        self.childObj.iotCollItems = chirldData.arrStr
      } */
      self.showTabPanel = chirldData.tab
    },
    // form弹窗
    updSubmitReady: function () {
      let self = this
      self.upd()
    },
    // form弹窗
    saveSubmitReady: function () {
      let self = this
      self.save()
    },
    // 初始化弹窗的数据
    resetModalData: function () {
      let self = this
      document.querySelector('.ivu-modal-footer').style.display = 'none'
      self.childObj = {}
      sessionStorage.manageDeviceInfo = ''
      sessionStorage.manageDeviceCollection = ''
    },
    // tableCheckbox变化
    tableCheckbox: function (selection) {
      let self = this
      self.tableCheckboxData = selection
      if (self.tableCheckboxData.length > 0) {
        self.deleteMoreDisabled = false
      } else {
        self.deleteMoreDisabled = true
      }
    },
    // 多项删除
    deleteMoreBtn: function () {
      let self = this
      if (self.tableCheckboxData.length > 0) {
        let arr = []
        self.tableCheckboxData.forEach((item) => {
          arr.push(item.id)
        })
        self.deleteMore(arr)
      }
    }
  }
}

</script>
